/**
 * app actions
 * @type {{chian, find, insert, findOne, findAndUpdate, findAndRemove, clear}}
 */

import {base64_decode} from '../../util/index';

function checkLicense(license) {
  
  var code = base64_decode(license);
  if(code.split('|')[1] != 'helloworld'){
    return false;
  };
  var time = (new Date()).getTime();
  var arr1 = code.split('|')[0].split("-");
  var date1=new Date(parseInt(arr1[0]),parseInt(arr1[1])-1,parseInt(arr1[2]),0,0,0);
  if(date1.getTime() < time){
    return false;
  }
  return true;
}

/**
 * 是否安装
 * @returns {function()}
 */
const isInstall = () => {
  return (dispatch) => {
    lokiApi('./dba/admin.json',function(mycollection){
      var doc = mycollection.findOne({});
      if(doc){
        if(!checkLicense(doc.license)){
          console.log('license')
          return Promise.resolve(dispatch({
            type : 'app_license',
            status : false
          }));
        }else{
          console.log('install')
          return Promise.resolve(dispatch({
            type : 'app_installed',
            status : true
          }));
        }
      }else{
        Promise.resolve(dispatch({
          type : 'app_installed',
          status : doc ? true : false
        }));
      }
    });
  }
}

/**
 * 是否登录
 * @returns {function()}
 */
const isLogin = () => {
  return (dispatch) => {
    return SessionModel.findOne({},function (err, doc) {
      if(!err){
        return Promise.resolve(dispatch({
          type : 'app_userinfo',
          userinfo : doc
        }));
      }else{
        return Promise.reject(err)
      }

    });
  }
}

/**
 * 增加授权
 * @param formdata
 * @returns {function()}
 */
const installLicense = (options) => {
  return (dispatch) => {
    return new Promise(function(resolve, reject){
      AdminModel.findOne({username: options.username}, function(err, doc){
        if( err ) {
          reject('数据库错误')
        }else{
          if( doc !== null) {
            if(options.password != doc.password){
              return reject('密码错误');
            };

            var license = options.license;
            if(!checkLicense(license)){
              return reject('授权码无效');
            };

            AdminModel.findAndUpdate({$loki:parseInt(doc.$loki)},options,(err,doc)=>{
              if(!err){
                resolve(dispatch({
                  type : 'app_installed',
                  status : true
                }));
              }else{
                reject('系统错误');
              }
            });

          }else{
            reject('该用户不存在');
          }
        }
      });

    });
  }
}

/**
 * 注册
 * @param formdata
 * @returns {function()}
 */
const installPost = (options) => {
  return (dispatch) => {
    return new Promise(function(resolve, reject){
      AdminModel.findOne({username: options.username}, function(err, doc){
        if( err ) {
          reject('数据库错误')
        }else{
          if( doc !== null) {
            reject('该用户已存在')
          }else{

            var license = options.license;
            if(!checkLicense(license)){
              return reject('授权码无效');
            };

            AdminModel.insert({
              username : options.username,
              password : options.password,
              license: options.license
            },(err,doc)=>{
              if(err){
                reject('系统错误');
              }else{
                resolve(dispatch({
                  type : 'app_installed',
                  status : true
                }));
              }
            })
          }
        }
      });

    });
  }
}

/**
 * 登录
 * @param formdata
 * @returns {function()}
 */
const loginPost = (options) => {
  return (dispatch) => {
    return new Promise(function(resolve, reject){
      AdminModel.findOne({username: options.username}, function(err, doc){
        if( err ) {
          reject('数据库错误')
        }else{
          if( doc === null) {
            reject('该用户不存在')
          }else{
            if(options.password === doc.password){

              SessionModel.insert({username:options.username,login:true});
              
              resolve(dispatch({
                type : 'app_userinfo',
                userinfo : doc
              }));
            }else{
              reject('密码错误')
            }
          }
        }
      });

    });
  }
}

/**
 * 退出登录
 * @returns {function()}
 */
const logout = () => {
  return (dispatch) => {
    SessionModel.clear();
    return Promise.resolve(dispatch({
      type : 'app_userinfo',
      userinfo : null
    }));
  }
}

/**
 * 修改loading状态
 * @param status
 * @returns {function()}
 */
const loading = (status) => {
  return (dispatch) => {
    return Promise.resolve(dispatch({
      type : 'app_loading',
      status
    }));
  }
}

/**
 * 信息提示
 * @param text
 * @returns {function()}
 */
const notice = (text) => {
  return (dispatch) => {
    return Promise.resolve(dispatch({
      type : 'app_notice',
      text
    }));
  }
}


export default {
  isLogin,
  isInstall,
  loginPost,
  installPost,
  installLicense,
  loading,
  logout,
  notice
}